<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
    @load="onLoad"
  >
    <comment-item
      v-for="(comment, index) in list"
      :key="index"
      :comment="comment"
      @reply-click="$emit('reply-click', $event)"
    ></comment-item>
  </van-list>
</template>
<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
// console.log(getComments)
export default {
  name: 'CommentList',
  components: { CommentItem },
  props: {
    source: {
      type: String,
      required: true,
    },

    list: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: 'a',

      validator(val) {
        return ['a', 'c'].includes(val)
      },
    },
  },

  data() {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      error: false,
      offset: null,
      limit: 5,
    }
  },

  methods: {
    async onLoad() {
      try {
        const { data } = await getComments({
          type: this.type,
          source: this.source,
          offset: this.offset,
          limit: this.limit,
        })
        console.log(data)
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        if (results.length === 0) {
          this.finished = true
        } else {
          this.offset = data.data.last_id
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }

      // 异步更新数据
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1)
      //   }
      //   // 加载状态结束
      //   this.loading = false

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true
      //   }
      // }, 500)
    },
  },
}
</script>
